package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.OrderNumberGenerator;
import com.ruoyi.system.domain.dto.XsOrderDto;
import com.ruoyi.system.domain.dto.XsOrderImportDto;
import com.ruoyi.system.domain.dto.XsTBImportDto;
import com.ruoyi.system.domain.vo.order.XsOrderListVo;
import com.ruoyi.system.domain.xs.XsOrder;
import com.ruoyi.system.domain.xs.XsOrderTb;
import com.ruoyi.system.mapper.XsOrderMapper;
import com.ruoyi.system.mapper.XsOrderTbMapper;
import com.ruoyi.system.service.IXsOrderTbService;
import com.ruoyi.system.service.IXsStoreService;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class XsOrderTbServiceImpl extends ServiceImpl<XsOrderTbMapper, XsOrderTb>
        implements IXsOrderTbService {

    @Autowired
    private IXsOrderTbService xsOrderTbService;

    @Autowired
    private IXsStoreService xsStoreService;

    @Autowired
    private XsOrderTbMapper xsOrderTbMapper;

    @Autowired
    private XsOrderMapper xsOrderMapper;

    private ThreadPoolTaskExecutor taskExecutor = SpringUtils.getBean("threadPoolTaskExecutor");

    /**
     * 查询订单列表
     *
     * @param orderDto
     * @return
     */
    @Override
    public List<XsOrderListVo> selectOrderList(XsOrderDto orderDto) {
        return xsOrderTbMapper.selectOrderList(orderDto);
    }

    /**
     * 导入淘宝订单数据
     * @param file
     */
    @Override
    public void importTBOrder(MultipartFile file) {
        ExcelUtil<XsTBImportDto> util = new ExcelUtil<XsTBImportDto>(XsTBImportDto.class);
        if (file.isEmpty()) {
            throw new GlobalException("上传的文件为空");
        }
        int count = 2;

        String orderId = null;
        try (InputStream inputStream = file.getInputStream()) {
            Workbook workbook = new XSSFWorkbook(inputStream); // 支持.xlsx格式的Excel文件
            // 表存在数据
            List<XsOrderTb> exist = new ArrayList<>();
            // 表不存在数据
            List<XsOrderTb> nonentity = new ArrayList<>();
            // 查询全部订单
            List<XsOrderTb> orderTBList = xsOrderTbService.lambdaQuery().list();

            Map<String, String> map = new HashMap<>();
            xsStoreService.lambdaQuery().list().forEach(store -> {
                map.put(store.getStoreName(), store.getStoreCode());
            });

            for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) {
                String sheetName = workbook.getSheetAt(sheetIndex).getSheetName();
                List<XsTBImportDto> importDtoList = util.importExcel(sheetName, file.getInputStream(), 0);
                if (StringUtils.isNotEmpty(importDtoList)) {
                    for (XsTBImportDto importDto : importDtoList) {

//                        if (StringUtils.isNotEmpty(importDto.getOrderStatus())) {
//                            Pattern pattern = Pattern.compile("关|闭");
//                            Matcher matcher = pattern.matcher(importDto.getOrderStatus());
//                            if (matcher.find()) {
//                                continue;
//                            }
//                        }
                        orderId = importDto.getAcookieId();
                        XsOrderTb orderTb = new XsOrderTb();

                        BeanUtil.copyProperties(importDto, orderTb);
                        orderTb.setUpdateBy(SecurityUtils.getUsername());
                        orderTb.setUpdateTime(DateUtils.getNowDate());
                        // 订单状态
                        XsOrder order = new XsOrder();
                        if (StringUtils.isNotEmpty(importDto.getOrderStatus())) {
                            orderTb.setStatusDescr(importDto.getOrderStatus());
                            if (Pattern.compile("成功").matcher(importDto.getOrderStatus()).find()) {
                                orderTb.setStatus("2");
//                                orderTb.setCheckSheet("1");
//                                orderTb.setIfBalance("1");
                                order.setStatus("2");
//                                order.setCheckSheet("3");
//                                order.setIfBalance("3");
                            }else if (Pattern.compile("已付款").matcher(importDto.getOrderStatus()).find()) {
                                orderTb.setStatus("3");
//                                orderTb.setCheckSheet("4");
//                                orderTb.setIfBalance("2");
                                order.setStatus("3");
//                                order.setCheckSheet("4");
//                                order.setIfBalance("2");
                            }else if (Pattern.compile("已发货").matcher(importDto.getOrderStatus()).find()) {
                                orderTb.setStatus("4");
//                                orderTb.setCheckSheet("4");
//                                orderTb.setIfBalance("2");
                                order.setStatus("4");
//                                order.setCheckSheet("4");
//                                order.setIfBalance("2");
                            }else {
                                orderTb.setStatus("1");
                                BigDecimal refund = new BigDecimal(orderTb.getRefund());
                                if(refund.doubleValue() > 0.0 && refund.doubleValue() < orderTb.getActualPayment().doubleValue()){
//                                    orderTb.setCheckSheet("4");
//                                    orderTb.setIfBalance("2");
//                                    order.setCheckSheet("4");
//                                    order.setIfBalance("2");
                                }
                            }
                        }



                        if (StringUtils.isNotEmpty(map)) {
                            Pattern pattern = Pattern.compile("笔|墨");
                            Matcher matcher = pattern.matcher(importDto.getStoreName());
                            if (matcher.find()) {
                                orderTb.setStoreCode(map.get("笔墨画千秋"));
                                orderTb.setOrderId(OrderNumberGenerator.generateOrderNumber("BM"));
                            } else {
                                orderTb.setStoreCode(map.get("回字格"));
                                orderTb.setOrderId(OrderNumberGenerator.generateOrderNumber("HZG"));
                            }
                        }
                        // 订单来源
                        orderTb.setOrderSource("千牛");

                        // 绩效月份 导入日期就是绩效月份
                        orderTb.setPerformance(DateUtils.dateTimeNow("yyyy-MM"));

                        if (StringUtils.isNotEmpty(orderTBList)) {
                            Set<String> orderIdList = orderTBList.stream().map(XsOrderTb::getAcookieId)
                                    .filter(id -> id != null && !id.isEmpty())
                                    .collect(Collectors.toSet());

                            if (orderIdList.contains(orderTb.getAcookieId())) {
                                orderTBList.stream().filter(o -> Objects.equals(o.getAcookieId(), importDto.getAcookieId())).findFirst().ifPresent(existingOrder -> {
                                    orderTb.setId(existingOrder.getId());
                                    orderTb.setOrderId(existingOrder.getOrderId());
                                    // 重复数据修改为重复报账状态
                                    if (StringUtils.isNotEmpty(importDto.getOrderStatus())) {
                                        orderTb.setStatusDescr(importDto.getOrderStatus());
                                        if (Pattern.compile("成功").matcher(importDto.getOrderStatus()).find()) {
                                            orderTb.setStatus("2");
//                                            orderTb.setCheckSheet("3");
//                                            orderTb.setIfBalance("3");
                                        }else if (Pattern.compile("已付款").matcher(importDto.getOrderStatus()).find()) {
                                            orderTb.setStatus("3");
//                                            orderTb.setCheckSheet("4");
//                                            orderTb.setIfBalance("2");
                                        }else if (Pattern.compile("已发货").matcher(importDto.getOrderStatus()).find()) {
                                            orderTb.setStatus("4");
//                                            orderTb.setCheckSheet("4");
//                                            orderTb.setIfBalance("2");
                                        }else {
                                            orderTb.setStatus("1");
                                            order.setStatus("1");
                                            BigDecimal refund = new BigDecimal(orderTb.getRefund());
                                            if(refund.doubleValue() > 0.0 && refund.doubleValue() < orderTb.getActualPayment().doubleValue()){
//                                                orderTb.setCheckSheet("4");
//                                                orderTb.setIfBalance("4");
                                            }
                                        }
                                    }
                                    //修改主订单数据
                                    xsOrderMapper.update(order,new UpdateWrapper<XsOrder>().eq("acookie_id",orderTb.getAcookieId()));

                                    orderTb.setUpdateBy(SecurityUtils.getUsername());
                                    orderTb.setUpdateTime(DateUtils.getNowDate());
                                    orderTb.setUpdateTime(DateUtils.getNowDate());
                                    exist.add(orderTb);
                                });
                            } else {
                                orderTb.setCreateBy(SecurityUtils.getUserId().toString());
                                orderTb.setCreateTime(DateUtils.getNowDate());
                                nonentity.add(orderTb);
                            }
                        } else {
                            orderTb.setCreateBy(SecurityUtils.getUserId().toString());
                            orderTb.setCreateTime(DateUtils.getNowDate());
                            nonentity.add(orderTb);
                        }
                        count++;
                    }
                } else {
                    throw new GlobalException("导入失败！excel第" + sheetIndex + 1 + "个工作表内数据为空");
                }
            }
            taskExecutor.submit(() -> {
                try {
                    if (exist.size() > 0) {
                        xsOrderTbService.updateBatchById(exist, 1000);
                    }
                    if (nonentity.size() > 0) {
                        xsOrderTbService.saveBatch(nonentity, 1000);
                    }
                } catch (Exception e) {
                    System.out.println("失败！" + e);
                }finally {
                    System.out.println("结束");
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            throw new GlobalException("文件读取错误");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage() + " -- " + count + " --- " + orderId);
        }
    }

    /**
     * 导入TB
     *
     * @param file
     */
    @Override
    public void importTB(MultipartFile file) {
        ExcelUtil<XsOrderImportDto> util = new ExcelUtil<XsOrderImportDto>(XsOrderImportDto.class);
        if (file.isEmpty()) {
            throw new GlobalException("上传的文件为空");
        }
        int count = 2;

        String orderId = null;
        try (InputStream inputStream = file.getInputStream()) {
            Workbook workbook = new XSSFWorkbook(inputStream); // 支持.xlsx格式的Excel文件

            // 表存在数据
            List<XsOrderTb> exist = new ArrayList<>();
            // 表不存在数据
            List<XsOrderTb> nonentity = new ArrayList<>();
            // 查询全部订单
            List<XsOrderTb> xsOrderList = lambdaQuery().list();

            Map<String, String> map = new HashMap<>();
            xsStoreService.lambdaQuery().list().forEach(store -> {
                map.put(store.getStoreName(), store.getStoreCode());
            });

            for (int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++) {
                String sheetName = workbook.getSheetAt(sheetIndex).getSheetName();
                Pattern pat = Pattern.compile("笔|墨");
                Matcher mat = pat.matcher(sheetName);
                String result = mat.find() ? "BM" : "HZG";

                List<XsOrderImportDto> importDtoList = util.importExcel(sheetName, file.getInputStream(), 0);

                if (StringUtils.isNotEmpty(importDtoList)) {
                    for (XsOrderImportDto importDto : importDtoList) {
                        orderId = importDto.getAcookieId();
                        XsOrderTb xsOrder = new XsOrderTb();

                        BeanUtil.copyProperties(importDto, xsOrder);
                        try {
                            xsOrder.setUpdateBy(SecurityUtils.getUsername());
                        } catch (Exception e) {
                            throw new GlobalException(e.getMessage());
                        }
                        xsOrder.setUpdateTime(DateUtils.getNowDate());

                        if (StringUtils.isNotEmpty(map)) {
                            Pattern pattern = Pattern.compile("笔|墨");
                            Matcher matcher = pattern.matcher(sheetName);
                            if (matcher.find()) {
                                xsOrder.setStoreCode(map.get("笔墨画千秋"));
                            } else {
                                xsOrder.setStoreCode(map.get("回字格"));
                            }
                        }

                        xsOrder.setOrderId(OrderNumberGenerator.generateOrderNumber(result.toUpperCase()));

                        if (StringUtils.isNotEmpty(xsOrder.getStatus())) {
                            xsOrder.setSettlementRemark(xsOrder.getStatus());
                            Pattern pattern = Pattern.compile("已结|代结|结");
                            Matcher matcher = pattern.matcher(xsOrder.getStatus());
                            if (matcher.find()) {
                                xsOrder.setStatus("6");
                            } else {
                                xsOrder.setStatus("4");
                            }
                        } else {
                            xsOrder.setStatus("4");
                        }

                        if (StringUtils.isNotEmpty(xsOrderList)) {
                            Set<String> orderIdList = xsOrderList.stream().map(XsOrderTb::getAcookieId)
                                    .filter(id -> id != null && !id.isEmpty())
                                    .collect(Collectors.toSet());

                            if (orderIdList.contains(xsOrder.getAcookieId())) {
                                xsOrderList.stream()
                                        .filter(o -> Objects.equals(o.getAcookieId(), importDto.getAcookieId()))
                                        .findFirst().ifPresent(existingOrder -> {
                                            xsOrder.setId(existingOrder.getId());
                                            xsOrder.setOrderId(existingOrder.getOrderId());
                                            xsOrder.setTitle(StringUtils.isEmpty(existingOrder.getTitle()) ? xsOrder.getTitle() : null);
                                            xsOrder.setPayTime(null);
                                            xsOrder.setUpdateBy(SecurityUtils.getUsername());
                                            xsOrder.setUpdateTime(DateUtils.getNowDate());
                                            exist.add(xsOrder);
                                        });
                            } else {
                                xsOrder.setCreateBy(SecurityUtils.getUsername());
                                xsOrder.setCreateTime(DateUtils.getNowDate());
                                nonentity.add(xsOrder);
                            }
                        } else {
                            xsOrder.setCreateBy(SecurityUtils.getUsername());
                            xsOrder.setCreateTime(DateUtils.getNowDate());
                            nonentity.add(xsOrder);
                        }
                        count++;
                    }
                } else {
                    throw new GlobalException("导入失败！excel第" + sheetIndex + 1 + "个工作表内数据为空");
                }
            }

            if (StringUtils.isNotEmpty(exist)) {
                xsOrderTbService.updateBatchById(exist);
            }
            if (StringUtils.isNotEmpty(nonentity)) {
                xsOrderTbService.saveBatch(nonentity);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new GlobalException("文件读取错误");
        } catch (Exception e) {
            throw new RuntimeException(e + "--" + count + "---" + orderId);
        }
    }

}
